package com.snowm.springboot.api;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.snowm.otdr.OTDRParser;
import com.snowm.otdr.domain.OTDRObj;
import com.snowm.otdr.utils.JSONUtil;

@Component
@Path("/sor")
public class RestEndPoint {
	
	private static final String ISO_8859_1 = "ISO-8859-1";

	private static final String GBK = "GBK";

	private static final String UTF_8 = "UTF-8";

	private Logger logger = LoggerFactory.getLogger(RestEndPoint.class);
	
	@Autowired
	private OTDRParser parser;

	@POST
	@Path("/parse")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response parse(FormDataMultiPart form) throws IOException {
		FormDataBodyPart filePart = form.getField("sor");
		InputStream fileInputStream = filePart.getValueAs(InputStream.class);
		FormDataContentDisposition formDataContentDisposition = filePart.getFormDataContentDisposition();
	 
		String sourceFileName = formDataContentDisposition.getFileName();
	 
		File tmpFile = File.createTempFile("sor-" + UUID.randomUUID(), null);
		try {
		    FileUtils.copyInputStreamToFile(fileInputStream, tmpFile);
		    logger.info("Recieved file:{}, saved to tmp file:{}!", sourceFileName, tmpFile);
		} catch (IOException ex) {
		    logger.info("Recieved file:{}, error to save to tmp file:{}!", sourceFileName, tmpFile, ex);
		}
		OTDRObj otdrObj = this.parser.parse(tmpFile);
		tmpFile.delete();
		String json = JSONUtil.encodePretty(otdrObj);
		if (logger.isDebugEnabled()) {
			String rs = json;
			logger.debug(rs);
		}
		
		String prefix = this.getPrefix(sourceFileName);
		prefix = new String(prefix.getBytes(UTF_8), ISO_8859_1);
		String fileName = prefix + ".json";
		Response response = Response.ok(json)
				.header("Content-Disposition", "attachment;filename=\"" + fileName + "\"")
				.header("Content-Length", json.getBytes(UTF_8).length)
				.header("ragma", "No-cache")
				.header("Cache-Control", "no-cache")
				.build();
		
		return response;
	}
	
	private String getPrefix(String fileName) {
		if (StringUtils.isBlank(fileName)) {
			return null;
		}
		int idx = fileName.lastIndexOf(".");
		if (idx > 0) {
			return fileName.substring(0, idx);
		}
		return fileName;
	}
}
